package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.Dish;
import com.itheima.dto.DishDTO;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.DishFlavorMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ding
 * @version 1.0
 * @description: TODO 菜品管理
 * @date 2022/6/5 14:51
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 功能描述: 根据categoryId查询菜品信息,返回到添加套餐的添加菜品页面
     *
     * @param categoryId
     * @return : java.util.List<com.itheima.entity.Dish>
     */
    @Override
    public List<DishDTO> findByCategoryId(Long categoryId, String name) {

        List<DishDTO> dishes = new ArrayList<>();
        if (categoryId == null && name == null) {
            return dishes;
        }
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        if (categoryId != null) {
            queryWrapper.eq(Dish::getCategoryId, categoryId);
        }
        if (name != null) {
            queryWrapper.like(Dish::getName, name.trim());
        }
        //2.执行查询,获取菜品列表
        List<Dish> dishList = dishMapper.selectList(queryWrapper);

        //3.遍历菜品列表，获取每个菜品的口味列表
        for (Dish dish : dishList) {
            DishDTO dishDTO = new DishDTO();
            //3.1 把菜品中属性，拷贝到DishDTO对象中（注意：source源数据对象、target目标数据对象，需要名称、类型一致才能拷贝）
            BeanUtils.copyProperties(dish, dishDTO);
            //3.2 根据菜品ID，获取菜品口味列表
            LambdaQueryWrapper<DishFlavor> dishFlavorWrapper = new LambdaQueryWrapper<>();
            dishFlavorWrapper.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(dishFlavorWrapper);
            //3.3 把口味列表数据存入DishDTO对象中
            dishDTO.setFlavors(dishFlavors);
            //3.4 把DishDTO
            dishes.add(dishDTO);
        }
        return dishes;
    }

}
